package com.company.nuwa.common.utils;

import com.company.nuwa.common.domain.ValidResult;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.apache.commons.collections4.CollectionUtils;
import org.hibernate.validator.HibernateValidator;

import java.util.Set;


/**
 * <p>校验工具类</p>
 *
 * @author lili
 * @version 1.0: ValidationUtils.java
 * @date 2020/5/18 13:06
 */
public class ValidationUtils {

    /**
     * 开启快速结束模式 failFast (true)
     */
    private static final Validator VALIDATOR = Validation.byProvider(HibernateValidator.class)
        .configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 校验对象
     *
     * @param t bean
     * @param groups 校验组
     * @return ValidResult
     */
    public static <T> ValidResult validateBean(T t, Class<?>... groups) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = VALIDATOR.validate(t, groups);
        boolean hasError = CollectionUtils.isNotEmpty(violationSet);
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return result;
    }

    public static <T> ValidResult validate(T obj) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = VALIDATOR.validate(obj);
        boolean hasError = CollectionUtils.isNotEmpty(violationSet);
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return result;
    }

    /**
     * 校验bean的某一个属性
     *
     * @param obj          bean
     * @param propertyName 属性名称
     * @return ValidResult
     */
    public static <T> ValidResult validateProperty(T obj, String propertyName) {
        ValidResult result = new ValidResult();
        Set<ConstraintViolation<T>> violationSet = VALIDATOR.validateProperty(obj, propertyName);
        boolean hasError = CollectionUtils.isNotEmpty(violationSet);
        result.setHasErrors(hasError);
        if (hasError) {
            for (ConstraintViolation<T> violation : violationSet) {
                result.addError(propertyName, violation.getMessage());
            }
        }
        return result;
    }

}
